<template>
  <div class="pick-material-add-page">
    <el-card shadow="never" class="breadcrumb-card">
      <div class="breadcrumb-content">
        <div class="breadcrumb-title">
          <el-icon class="breadcrumb-icon">
            <Box />
          </el-icon>
          <div>
            <p class="breadcrumb-subtitle">仓库管理 · 生产领料</p>
            <h2 class="breadcrumb-heading">
              {{ isEditMode ? "编辑生产领料" : "新增生产领料" }}
            </h2>
          </div>
        </div>
        <el-breadcrumb :separator-icon="ArrowRight">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>仓库管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/PickMaterialList' }">
            生产领料
          </el-breadcrumb-item>
          <el-breadcrumb-item>
            {{ isEditMode ? "编辑" : "新增" }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </el-card>

    <el-card shadow="never" class="form-card">
      <div class="page-header">
        <div class="page-header__content">
          <div class="page-header__title">
            <div class="page-header__icon-wrapper">
              <el-icon class="page-header__icon"><DocumentAdd /></el-icon>
            </div>
            <div class="page-header__text">
              <h2>{{ isEditMode ? "编辑生产领料" : "新增生产领料" }}</h2>
              <p class="page-header__desc">
                {{ isEditMode ? "修改生产领料单信息" : "创建新的生产领料单" }}
              </p>
            </div>
          </div>
          <el-tag
            :type="isEditMode ? 'warning' : 'success'"
            effect="dark"
            size="large"
            class="page-header__tag"
          >
            <el-icon class="tag-icon"><Box /></el-icon>
            {{ isEditMode ? "编辑模式" : "新增模式" }}
          </el-tag>
        </div>
      </div>

      <el-form
        ref="formRef"
        :model="formModel"
        :rules="rules"
        label-width="120px"
        class="pick-material-form"
      >
        <!-- 基础信息 -->
        <div class="form-section">
          <div class="section-header">
            <div class="section-header__main">
              <div class="section-header__icon">
                <el-icon><DocumentAdd /></el-icon>
              </div>
              <div>
                <p class="section-title">基础信息</p>
                <p class="section-subtitle">完善领料单的基础内容</p>
              </div>
            </div>
            <el-tag type="success" effect="light" size="small">
              必填字段
            </el-tag>
          </div>

          <el-row :gutter="24">
            <!-- 左侧列 -->
            <el-col :span="12">
              <el-form-item label="领料单编号" prop="pickMaterialCode" required>
                <div class="code-field-wrapper">
                  <el-input
                    v-model="formModel.pickMaterialCode"
                    :placeholder="autoGenerateCode ? '自动生成编号' : '请输入'"
                    :disabled="autoGenerateCode"
                    clearable
                    class="code-input"
                    style="width: 270px"
                  >
                    <template #prefix>
                      <el-icon><Tickets /></el-icon>
                    </template>
                  </el-input>
                  <div class="code-switch-wrapper">
                    <el-switch
                      v-model="autoGenerateCode"
                      @change="handleAutoGenerateCodeChange"
                      inline-prompt
                      active-text="系统编号"
                      inactive-text="手动输入"
                    />
                  </div>
                </div>
              </el-form-item>
            </el-col>
            <!-- 右侧列 -->
            <el-col :span="12">
              <el-form-item label="领料单名称" prop="pickMaterialName" required>
                <el-input
                  v-model="formModel.pickMaterialName"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <!-- 左侧列 -->
            <el-col :span="12">
              <el-form-item label="领料日期" prop="pickMaterialDate" required>
                <el-date-picker
                  v-model="formModel.pickMaterialDate"
                  type="date"
                  placeholder="请选择日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                  :prefix-icon="Calendar"
                />
              </el-form-item>
            </el-col>
            <!-- 右侧列 -->
            <el-col :span="12">
              <el-form-item label="领料人" prop="picker">
                <div class="picker-field-wrapper">
                  <el-input
                    v-model="formModel.picker"
                    placeholder="请选择领料人"
                    clearable
                    style="flex: 1"
                  />
                  <el-button
                    type="primary"
                    :icon="Grid"
                    @click="openUserDialog"
                    class="picker-select-btn"
                  >
                    选择
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <!-- 左侧列 -->
            <el-col :span="12">
              <el-form-item label="工单名称" prop="workOrderName" required>
                <div class="select-field-wrapper">
                  <el-input
                    v-model="formModel.workOrderName"
                    placeholder="请选择生产工单"
                    disabled
                    style="flex: 1"
                  />
                  <el-button
                    type="primary"
                    :icon="Grid"
                    class="select-btn"
                    @click="openWorkOrderDialog"
                  >
                    选择
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
            <!-- 右侧列 -->
            <el-col :span="12">
              <el-form-item label="工单编号" prop="workOrderCode">
                <el-input
                  v-model="formModel.workOrderCode"
                  placeholder="请选择生产工单"
                  disabled
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <!-- 左侧列 -->
            <el-col :span="12">
              <el-form-item label="任务名称" prop="taskName" required>
                <div class="select-field-wrapper">
                  <el-input
                    v-model="formModel.taskName"
                    placeholder="请选择任务"
                    disabled
                    style="flex: 1"
                  />
                  <el-button
                    type="primary"
                    :icon="Grid"
                    class="select-btn"
                    @click="openTaskDialog"
                  >
                    选择
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
            <!-- 右侧列 -->
            <el-col :span="12">
              <el-form-item label="任务编号" prop="taskCode">
                <el-input
                  v-model="formModel.taskCode"
                  placeholder="请选择任务"
                  disabled
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <!-- 左侧列 -->
            <el-col :span="12">
              <el-form-item label="工艺路线" prop="processRoute">
                <el-input
                  v-model="formModel.processRoute"
                  placeholder="请选择任务"
                  disabled
                  clearable
                />
              </el-form-item>
            </el-col>
            <!-- 右侧列 -->
            <el-col :span="12">
              <el-form-item label="工序名称" prop="processName">
                <el-input
                  v-model="formModel.processName"
                  placeholder="请选择任务"
                  disabled
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 备注（跨两列） -->
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formModel.remark"
              type="textarea"
              :rows="4"
              placeholder="请输入"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </div>

        <!-- 物料明细 -->
        <div class="form-section">
          <div class="section-header">
            <div class="section-header__main">
              <div class="section-header__icon">
                <el-icon><List /></el-icon>
              </div>
              <div>
                <p class="section-title">领料明细</p>
                <p class="section-subtitle">添加领料信息</p>
              </div>
            </div>
            <div class="section-header__actions">
              <el-button
                type="primary"
                :icon="Plus"
                @click="handleAddDetail"
                class="add-detail-btn"
                >添加领料明细</el-button
              >
            </div>
          </div>

          <div v-if="formModel.detail.length === 0" class="empty-detail">
            <el-empty description="暂无物料明细，请点击上方按钮添加" />
          </div>

          <div
            v-for="(item, index) in formModel.detail"
            :key="index"
            class="detail-item"
          >
            <div class="detail-item__header">
              <div class="detail-item__title">
                <el-icon class="detail-item__icon"><Box /></el-icon>
                <span>领料明细 {{ index + 1 }}</span>
              </div>
              <el-button
                type="danger"
                :icon="Delete"
                link
                size="small"
                @click="handleRemoveDetail(index)"
                >删除</el-button
              >
            </div>

            <el-form :model="item" label-width="100px" class="detail-form">
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="物料名称" required>
                    <el-input
                      v-model="item.materialName"
                      placeholder="请输入物料名称"
                      clearable
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="物料编号" required>
                    <el-input
                      v-model="item.materialCode"
                      placeholder="请输入物料编号"
                      clearable
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="规格型号">
                    <el-input
                      v-model="item.specModel"
                      placeholder="请输入规格型号"
                      clearable
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="单位">
                    <el-input
                      v-model="item.unit"
                      placeholder="请输入单位"
                      clearable
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="当前库存">
                    <el-input-number
                      v-model="item.currentStock"
                      :min="0"
                      :precision="2"
                      placeholder="当前库存"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="领用数量" required>
                    <el-input-number
                      v-model="item.pickQuantity"
                      :min="0"
                      :precision="2"
                      placeholder="请输入领用数量"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="批次号">
                    <el-input
                      v-model="item.batchNo"
                      placeholder="请输入批次号"
                      clearable
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="仓库名称">
                    <el-input
                      v-model="item.warehouseName"
                      placeholder="请输入仓库名称"
                      clearable
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="备注">
                <el-input
                  v-model="item.itemRemark"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入备注"
                  maxlength="200"
                  show-word-limit
                />
              </el-form-item>
            </el-form>
          </div>
        </div>

        <!-- 表单操作按钮 -->
        <div class="form-actions">
          <el-button @click="handleCancel">取消</el-button>
          <el-button
            type="primary"
            :loading="submitLoading"
            @click="handleSubmit"
            >{{ isEditMode ? "保存修改" : "提交" }}</el-button
          >
        </div>
      </el-form>
    </el-card>

    <!-- 任务选择对话框 -->
    <el-dialog
      v-model="taskDialogVisible"
      title="选择工单任务"
      width="1200px"
      :close-on-click-modal="false"
      append-to-body
      class="task-dialog"
    >
      <!-- 工单信息显示 -->
      <div class="task-dialog-header">
        <div class="work-order-info">
          <span class="info-label">工单编号:</span>
          <span class="info-value">{{
            formModel.workOrderCode || "未选择"
          }}</span>
        </div>
        <div class="work-order-info">
          <span class="info-label">工单名称:</span>
          <span class="info-value">{{
            formModel.workOrderName || "未选择"
          }}</span>
        </div>
      </div>

      <!-- 搜索区域 -->
      <div class="dialog-search-area">
        <el-form
          :inline="true"
          :model="taskQueryForm"
          label-width="auto"
          class="search-form"
        >
          <el-form-item label="">
            <el-input
              v-model="taskQueryForm.taskKeyword"
              placeholder="请输入任务编号/名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="">
            <div class="select-input-wrapper">
              <el-input
                v-model="taskQueryForm.processName"
                placeholder="工序名称"
                clearable
                style="width: 180px"
              />
              <el-button
                type="primary"
                :icon="Grid"
                @click="handleProcessNameSelect"
                class="select-icon-btn"
              />
            </div>
          </el-form-item>
          <el-form-item label="">
            <div class="select-input-wrapper">
              <el-input
                v-model="taskQueryForm.taskOwner"
                placeholder="请选择任务负责人"
                clearable
                style="width: 180px"
              />
              <el-button
                type="primary"
                :icon="Grid"
                @click="handleTaskOwnerSelect"
                class="select-icon-btn"
              />
            </div>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleTaskReset">重置</el-button>
            <el-button type="primary" @click="handleTaskQuery">查询</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table
        :data="filteredTaskList"
        border
        stripe
        height="400px"
        v-loading="taskLoading"
        @row-click="handleTaskRowClick"
        highlight-current-row
        class="task-table"
      >
        <el-table-column width="100" label="序号" align="center">
          <template #default="{ $index, row }">
            <div class="radio-with-index">
              <el-radio
                v-model="selectedTaskId"
                :label="row.id"
                @change="handleTaskSelect(row)"
                class="task-radio"
              />
              <span class="index-number">
                {{
                  (taskPagination.pageIndex - 1) * taskPagination.pageSize +
                  $index +
                  1
                }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="taskCode" label="任务编号" min-width="140" />
        <el-table-column prop="taskName" label="任务名称" min-width="180" />
        <el-table-column prop="siteName" label="站点名称" min-width="120" />
        <el-table-column prop="processRoute" label="工艺路线" min-width="140" />
        <el-table-column prop="processName" label="工序名称" min-width="120" />
        <el-table-column prop="processCode" label="工序编号" min-width="140" />
        <el-table-column prop="taskOwner" label="任务负责人" min-width="120" />
      </el-table>

      <!-- 分页 -->
      <div class="dialog-pagination">
        <el-pagination
          v-model:current-page="taskPagination.pageIndex"
          v-model:page-size="taskPagination.pageSize"
          :total="taskPagination.totalCount"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleTaskSizeChange"
          @current-change="handleTaskPageChange"
        />
      </div>

      <!-- 底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancelTask">取消</el-button>
          <el-button type="primary" @click="handleConfirmTask">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 工单选择对话框 -->
    <el-dialog
      v-model="workOrderDialogVisible"
      title="选择生产工单"
      width="1000px"
      :close-on-click-modal="false"
      append-to-body
      class="work-order-dialog"
    >
      <!-- 搜索区域 -->
      <div class="dialog-search-area">
        <el-form
          :inline="true"
          :model="workOrderQueryForm"
          label-width="auto"
          class="search-form"
        >
          <el-form-item label="">
            <el-input
              v-model="workOrderQueryForm.workOrderKeyword"
              placeholder="请输入工单编号/名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="">
            <el-input
              v-model="workOrderQueryForm.productKeyword"
              placeholder="请输入产品编号/名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="">
            <el-select
              v-model="workOrderQueryForm.productType"
              placeholder="请选择产品类型"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="type in productTypeOptions"
                :key="type.value"
                :label="type.label"
                :value="type.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleWorkOrderReset">重置</el-button>
            <el-button type="primary" @click="handleWorkOrderQuery"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table
        :data="filteredWorkOrderList"
        border
        stripe
        height="400px"
        v-loading="workOrderLoading"
        @row-click="handleWorkOrderRowClick"
        highlight-current-row
        class="work-order-table"
      >
        <el-table-column width="100" label="序号" align="center">
          <template #default="{ $index, row }">
            <div class="radio-with-index">
              <el-radio
                v-model="selectedWorkOrderId"
                :label="row.id"
                @change="handleWorkOrderSelect(row)"
                class="work-order-radio"
              />
              <span class="index-number">
                {{
                  (workOrderPagination.pageIndex - 1) *
                    workOrderPagination.pageSize +
                  $index +
                  1
                }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="workOrderCode"
          label="工单编号"
          min-width="140"
        />
        <el-table-column
          prop="workOrderName"
          label="工单名称"
          min-width="180"
        />
        <el-table-column prop="productName" label="产品名称" min-width="140" />
        <el-table-column prop="productCode" label="产品编号" min-width="140" />
        <el-table-column prop="specModel" label="规格型号" min-width="120" />
        <el-table-column prop="productType" label="产品类型" width="100" />
        <el-table-column prop="unit" label="单位" width="80" />
      </el-table>

      <!-- 分页 -->
      <div class="dialog-pagination">
        <el-pagination
          v-model:current-page="workOrderPagination.pageIndex"
          v-model:page-size="workOrderPagination.pageSize"
          :total="workOrderPagination.totalCount"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleWorkOrderSizeChange"
          @current-change="handleWorkOrderPageChange"
        />
      </div>

      <!-- 底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancelWorkOrder">取消</el-button>
          <el-button type="primary" @click="handleConfirmWorkOrder"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 工序名称选择对话框 -->
    <el-dialog
      v-model="processNameDialogVisible"
      title="选择工序名称"
      width="500px"
      :close-on-click-modal="false"
      append-to-body
    >
      <div class="option-list">
        <div
          v-for="name in processNameOptions"
          :key="name"
          class="option-item"
          @click="handleConfirmProcessName(name)"
        >
          {{ name }}
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="processNameDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 任务负责人选择对话框 -->
    <el-dialog
      v-model="taskOwnerDialogVisible"
      title="选择任务负责人"
      width="500px"
      :close-on-click-modal="false"
      append-to-body
    >
      <div class="option-list">
        <div
          v-for="name in taskOwnerOptions"
          :key="name"
          class="option-item"
          @click="handleConfirmTaskOwner(name)"
        >
          {{ name }}
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="taskOwnerDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 物料选择对话框 -->
    <el-dialog
      v-model="materialDialogVisible"
      title="添加物料"
      width="900px"
      :close-on-click-modal="false"
      append-to-body
      class="material-select-dialog"
    >
      <!-- 搜索和筛选区域 -->
      <div class="material-dialog-search">
        <el-form
          :inline="true"
          :model="materialSearchForm"
          class="material-search-form"
        >
          <el-form-item label="">
            <el-input
              v-model="materialSearchForm.materialKeyword"
              placeholder="请输入物料编号/名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="">
            <el-select
              v-model="materialSearchForm.unit"
              placeholder="请选择单位"
              clearable
              style="width: 150px"
            >
              <el-option
                v-for="unit in unitOptions"
                :key="unit"
                :label="unit"
                :value="unit"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleMaterialReset">重置</el-button>
            <el-button type="primary" @click="handleMaterialQuery"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table
        ref="materialTableRef"
        :data="materialTableData"
        border
        stripe
        height="400px"
        v-loading="materialLoading"
        row-key="id"
        @selection-change="handleMaterialSelectionChange"
        class="material-table"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" width="80" align="center">
          <template #default="{ $index }">
            {{
              (materialPagination.pageIndex - 1) * materialPagination.pageSize +
              $index +
              1
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="materialNo"
          label="物料编号"
          min-width="140"
          show-overflow-tooltip
        />
        <el-table-column
          prop="materialName"
          label="物料名称"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          prop="specification"
          label="规格型号"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column prop="unit" label="单位" width="80" align="center" />
      </el-table>

      <!-- 分页 -->
      <div class="material-dialog-pagination">
        <span class="pagination-total"
          >共{{ materialPagination.totalCount }}条</span
        >
        <el-pagination
          v-model:current-page="materialPagination.pageIndex"
          v-model:page-size="materialPagination.pageSize"
          :total="materialPagination.totalCount"
          :page-sizes="[10, 20, 30, 50]"
          layout="prev, pager, next"
          background
          @size-change="handleMaterialSizeChange"
          @current-change="handleMaterialPageChange"
        />
        <span class="pagination-jumper">
          前往
          <el-input-number
            v-model="jumpPage"
            :min="1"
            :max="Math.max(1, materialPagination.pageCount)"
            :controls="false"
            style="width: 60px"
            @keyup.enter="handleMaterialJumpPage"
          />
          页
        </span>
      </div>

      <!-- 底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancelMaterial">取消</el-button>
          <el-button type="primary" @click="handleConfirmMaterial"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 用户选择对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      title="领料人"
      width="800px"
      :close-on-click-modal="false"
      append-to-body
      class="picker-user-dialog"
    >
      <!-- 已选择项显示 -->
      <div class="selected-items" v-if="selectedUser">
        <el-tag
          closable
          type="primary"
          @close="handleRemoveSelectedUser"
          class="selected-tag"
        >
          {{ selectedUser.username }}
        </el-tag>
      </div>

      <!-- 搜索框 -->
      <div class="search-box">
        <el-input
          v-model="userKeyword"
          placeholder="请输入"
          clearable
          class="search-input"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 主要内容区域：左侧班组，右侧人员列表 -->
      <div class="dialog-content">
        <!-- 左侧：班组列表 -->
        <div class="team-list-container">
          <div class="team-list-header">班组</div>
          <div class="team-list" v-loading="userLoading">
            <div
              v-for="team in teamList"
              :key="team.value"
              :class="['team-item', { active: selectedTeam === team.value }]"
              @click="handleTeamSelect(team.value)"
            >
              {{ team.label }}
            </div>
          </div>
        </div>

        <!-- 右侧：人员列表 -->
        <div class="user-list-container">
          <div class="user-list" v-loading="userLoading">
            <div
              v-for="user in filteredUserList"
              :key="user.id"
              :class="['user-item', { selected: selectedUser?.id === user.id }]"
              @click="handleUserSelect(user)"
            >
              <el-radio
                :model-value="selectedUser?.id === user.id"
                :label="user.id"
                @click.stop="handleUserSelect(user)"
                class="user-radio"
              >
                <span class="user-name">{{ user.username }}</span>
              </el-radio>
            </div>
            <div v-if="filteredUserList.length === 0" class="empty-user">
              <el-empty description="暂无人员数据" :image-size="80" />
            </div>
          </div>
        </div>
      </div>

      <!-- 底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancelUser">取消</el-button>
          <el-button type="primary" @click="handleConfirmUser">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
  ArrowRight,
  Box,
  Calendar,
  DocumentAdd,
  Tickets,
  List,
  Plus,
  Delete,
  Lightning,
  EditPen,
  User,
  Search,
  Grid,
} from "@element-plus/icons-vue";
import { onMounted, reactive, ref, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
import https from "@/Http/http";

// 用户DTO类型定义
interface UserDto {
  id: number;
  username: string;
  usernumber?: string;
  accountname?: string;
  usersex?: string;
  phone?: string;
  emails?: string;
  status?: number;
  roleid?: number;
  rolename?: string;
  organid?: number;
  organname?: string;
  jobid?: number;
  jobname?: string;
}

// API响应类型定义
interface ApiPageing<T> {
  code: number;
  msg?: string;
  data: T[];
  totalCount?: number;
  pageCount?: number;
  // 兼容后端可能返回的大写属性
  Code?: number;
  Msg?: string;
  Data?: T[];
  TotalCount?: number;
  PageCount?: number;
}

const router = useRouter();
const route = useRoute();

// 编辑模式判断
const isEditMode = computed(() => {
  return !!route.query.editId;
});

// 表单引用
const formRef = ref<FormInstance>();
const submitLoading = ref(false);

// 自动生成编码开关状态
const autoGenerateCode = ref(false);

// 用户选择对话框相关状态
const userDialogVisible = ref(false);
const userKeyword = ref("");
const userList = ref<UserDto[]>([]);
const userLoading = ref(false);
const selectedUser = ref<UserDto | null>(null);
const selectedTeam = ref<string | null>(null);

// 工单选择对话框相关状态
const workOrderDialogVisible = ref(false);
const workOrderLoading = ref(false);
const selectedWorkOrder = ref<WorkOrderItem | null>(null);
const selectedWorkOrderId = ref<number | null>(null);
const workOrderQueryForm = reactive({
  workOrderKeyword: "",
  productKeyword: "",
  productType: null as string | null,
});
const workOrderPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
});

// 工单数据类型定义
interface WorkOrderItem {
  id: number;
  workOrderCode: string;
  workOrderName: string;
  productName: string;
  productCode: string;
  specModel: string;
  productType: string;
  unit: string;
}

// 产品类型选项
const productTypeOptions = [
  { label: "成品", value: "成品" },
  { label: "半成品", value: "半成品" },
  { label: "原材料", value: "原材料" },
];

// 生成关于电脑键盘的工单数据
const generateWorkOrderData = (): WorkOrderItem[] => {
  const keyboardTypes = [
    "机械键盘",
    "薄膜键盘",
    "静电容键盘",
    "游戏键盘",
    "办公键盘",
    "无线键盘",
    "有线键盘",
    "RGB背光键盘",
    "87键键盘",
    "104键键盘",
  ];
  const colors = [
    "黑色",
    "白色",
    "蓝色",
    "红色",
    "粉色",
    "灰色",
    "银色",
    "金色",
  ];
  const brands = [
    "罗技",
    "雷蛇",
    "樱桃",
    "海盗船",
    "赛睿",
    "斐尔可",
    "阿米洛",
    "IKBC",
  ];
  const units = ["个", "台", "套"];

  const data: WorkOrderItem[] = [];
  for (let i = 1; i <= 50; i++) {
    const typeIndex = Math.floor(Math.random() * keyboardTypes.length);
    const colorIndex = Math.floor(Math.random() * colors.length);
    const brandIndex = Math.floor(Math.random() * brands.length);
    const unitIndex = Math.floor(Math.random() * units.length);

    const keyboardType = keyboardTypes[typeIndex] || "";
    const color = colors[colorIndex] || "";
    const brand = brands[brandIndex] || "";
    const unit = units[unitIndex] || "";

    const productType =
      i % 3 === 0 ? "成品" : i % 3 === 1 ? "半成品" : "原材料";

    data.push({
      id: i,
      workOrderCode: `GDBH${String(i).padStart(4, "0")}`,
      workOrderName: `${brand}${keyboardType}生产工单`,
      productName: `${brand}${keyboardType}`,
      productCode: `CPBH${String(i).padStart(5, "0")}`,
      specModel: color,
      productType: productType,
      unit: unit,
    });
  }
  return data;
};

// 工单数据源
const workOrderData = ref<WorkOrderItem[]>(generateWorkOrderData());

// 过滤后的工单列表（不分页）
const filteredWorkOrderListAll = computed(() => {
  let list = workOrderData.value;

  // 按工单编号/名称筛选
  if (workOrderQueryForm.workOrderKeyword.trim()) {
    const keyword = workOrderQueryForm.workOrderKeyword.trim().toLowerCase();
    list = list.filter(
      (item) =>
        item.workOrderCode.toLowerCase().includes(keyword) ||
        item.workOrderName.toLowerCase().includes(keyword)
    );
  }

  // 按产品编号/名称筛选
  if (workOrderQueryForm.productKeyword.trim()) {
    const keyword = workOrderQueryForm.productKeyword.trim().toLowerCase();
    list = list.filter(
      (item) =>
        item.productCode.toLowerCase().includes(keyword) ||
        item.productName.toLowerCase().includes(keyword)
    );
  }

  // 按产品类型筛选
  if (workOrderQueryForm.productType) {
    list = list.filter(
      (item) => item.productType === workOrderQueryForm.productType
    );
  }

  return list;
});

// 过滤后的工单列表（分页）
const filteredWorkOrderList = computed(() => {
  const list = filteredWorkOrderListAll.value;

  // 更新总数
  workOrderPagination.totalCount = list.length;

  // 分页
  const start =
    (workOrderPagination.pageIndex - 1) * workOrderPagination.pageSize;
  const end = start + workOrderPagination.pageSize;
  return list.slice(start, end);
});

// 打开工单选择对话框
const openWorkOrderDialog = (): void => {
  workOrderDialogVisible.value = true;
  workOrderQueryForm.workOrderKeyword = "";
  workOrderQueryForm.productKeyword = "";
  workOrderQueryForm.productType = null;
  workOrderPagination.pageIndex = 1;

  // 如果已有选中的工单，设置为选中状态
  if (formModel.workOrderCode) {
    const existingWorkOrder = workOrderData.value.find(
      (item) => item.workOrderCode === formModel.workOrderCode
    );
    if (existingWorkOrder) {
      selectedWorkOrder.value = existingWorkOrder;
      selectedWorkOrderId.value = existingWorkOrder.id;
    } else {
      selectedWorkOrder.value = null;
      selectedWorkOrderId.value = null;
    }
  } else {
    selectedWorkOrder.value = null;
    selectedWorkOrderId.value = null;
  }
};

// 工单查询
const handleWorkOrderQuery = (): void => {
  workOrderPagination.pageIndex = 1;
};

// 工单重置
const handleWorkOrderReset = (): void => {
  workOrderQueryForm.workOrderKeyword = "";
  workOrderQueryForm.productKeyword = "";
  workOrderQueryForm.productType = null;
  workOrderPagination.pageIndex = 1;
};

// 工单分页大小改变
const handleWorkOrderSizeChange = (size: number): void => {
  workOrderPagination.pageSize = size;
  workOrderPagination.pageIndex = 1;
};

// 工单页码改变
const handleWorkOrderPageChange = (page: number): void => {
  workOrderPagination.pageIndex = page;
};

// 工单行点击
const handleWorkOrderRowClick = (row: WorkOrderItem): void => {
  selectedWorkOrder.value = row;
  selectedWorkOrderId.value = row.id;
};

// 工单选择
const handleWorkOrderSelect = (row: WorkOrderItem): void => {
  selectedWorkOrder.value = row;
  selectedWorkOrderId.value = row.id;
};

// 取消工单选择
const handleCancelWorkOrder = (): void => {
  workOrderDialogVisible.value = false;
  selectedWorkOrder.value = null;
  selectedWorkOrderId.value = null;
};

// 确认工单选择
const handleConfirmWorkOrder = (): void => {
  if (!selectedWorkOrder.value || !selectedWorkOrderId.value) {
    ElMessage.warning("请选择生产工单");
    return;
  }
  formModel.workOrderName = selectedWorkOrder.value.workOrderName;
  formModel.workOrderCode = selectedWorkOrder.value.workOrderCode;
  workOrderDialogVisible.value = false;
  selectedWorkOrderId.value = null;
};

// 任务选择对话框相关状态
const taskDialogVisible = ref(false);
const taskLoading = ref(false);
const selectedTask = ref<TaskItem | null>(null);
const selectedTaskId = ref<number | null>(null);
const taskQueryForm = reactive({
  taskKeyword: "",
  processName: "",
  taskOwner: "",
});
const taskPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
});

// 任务数据类型定义
interface TaskItem {
  id: number;
  taskCode: string;
  taskName: string;
  siteName: string;
  processRoute: string;
  processName: string;
  processCode: string;
  taskOwner: string;
}

// 工序名称选项（关于电脑键盘）
const processNameOptions = [
  "键盘组装",
  "键帽安装",
  "轴体焊接",
  "PCB测试",
  "外壳加工",
  "背光调试",
  "按键校准",
  "质量检测",
  "包装工序",
  "出厂检验",
];

// 任务负责人选项（关于电脑键盘）
const taskOwnerOptions = [
  "赵子龙",
  "关羽",
  "张飞",
  "刘备",
  "诸葛亮",
  "黄忠",
  "马超",
  "赵云",
  "魏延",
  "姜维",
];

// 站点名称选项
const siteNameOptions = ["站点一", "站点二", "站点三", "站点四", "站点五"];

// 工艺路线选项
const processRouteOptions = [
  "工艺路线一",
  "工艺路线二",
  "工艺路线三",
  "工艺路线四",
  "工艺路线五",
];

// 生成关于电脑键盘的任务数据
const generateTaskData = (): TaskItem[] => {
  const keyboardTypes = [
    "机械键盘",
    "薄膜键盘",
    "静电容键盘",
    "游戏键盘",
    "办公键盘",
    "无线键盘",
    "有线键盘",
    "RGB背光键盘",
    "87键键盘",
    "104键键盘",
  ];
  const brands = [
    "罗技",
    "雷蛇",
    "樱桃",
    "海盗船",
    "赛睿",
    "斐尔可",
    "阿米洛",
    "IKBC",
  ];

  const data: TaskItem[] = [];
  for (let i = 1; i <= 50; i++) {
    const typeIndex = Math.floor(Math.random() * keyboardTypes.length);
    const brandIndex = Math.floor(Math.random() * brands.length);
    const processIndex = Math.floor(Math.random() * processNameOptions.length);
    const ownerIndex = Math.floor(Math.random() * taskOwnerOptions.length);
    const siteIndex = Math.floor(Math.random() * siteNameOptions.length);
    const routeIndex = Math.floor(Math.random() * processRouteOptions.length);

    const keyboardType = keyboardTypes[typeIndex] || "";
    const brand = brands[brandIndex] || "";
    const processName = processNameOptions[processIndex] || "";
    const taskOwner = taskOwnerOptions[ownerIndex] || "";
    const siteName = siteNameOptions[siteIndex] || "";
    const processRoute = processRouteOptions[routeIndex] || "";

    data.push({
      id: i,
      taskCode: `RWBH${String(i).padStart(4, "0")}`,
      taskName: `${brand}${keyboardType}生产工单任务${
        i % 3 === 0 ? "一" : i % 3 === 1 ? "二" : "三"
      }`,
      siteName: siteName,
      processRoute: processRoute,
      processName: processName,
      processCode: `GXBH${String(i).padStart(5, "0")}`,
      taskOwner: taskOwner,
    });
  }
  return data;
};

// 任务数据源
const taskData = ref<TaskItem[]>(generateTaskData());

// 过滤后的任务列表（不分页）
const filteredTaskListAll = computed(() => {
  let list = taskData.value;

  // 按任务编号/名称筛选
  if (taskQueryForm.taskKeyword.trim()) {
    const keyword = taskQueryForm.taskKeyword.trim().toLowerCase();
    list = list.filter(
      (item) =>
        item.taskCode.toLowerCase().includes(keyword) ||
        item.taskName.toLowerCase().includes(keyword)
    );
  }

  // 按工序名称筛选
  if (taskQueryForm.processName.trim()) {
    const keyword = taskQueryForm.processName.trim().toLowerCase();
    list = list.filter((item) =>
      item.processName.toLowerCase().includes(keyword)
    );
  }

  // 按任务负责人筛选
  if (taskQueryForm.taskOwner.trim()) {
    const keyword = taskQueryForm.taskOwner.trim().toLowerCase();
    list = list.filter((item) =>
      item.taskOwner.toLowerCase().includes(keyword)
    );
  }

  return list;
});

// 过滤后的任务列表（分页）
const filteredTaskList = computed(() => {
  const list = filteredTaskListAll.value;

  // 更新总数
  taskPagination.totalCount = list.length;

  // 分页
  const start = (taskPagination.pageIndex - 1) * taskPagination.pageSize;
  const end = start + taskPagination.pageSize;
  return list.slice(start, end);
});

// 打开任务选择对话框
const openTaskDialog = (): void => {
  // 检查是否已选择工单
  if (!formModel.workOrderCode || !formModel.workOrderName) {
    ElMessage.warning("请先选择生产工单");
    return;
  }

  taskDialogVisible.value = true;
  taskQueryForm.taskKeyword = "";
  taskQueryForm.processName = "";
  taskQueryForm.taskOwner = "";
  taskPagination.pageIndex = 1;

  // 如果已有选中的任务，设置为选中状态
  if (formModel.taskCode) {
    const existingTask = taskData.value.find(
      (item) => item.taskCode === formModel.taskCode
    );
    if (existingTask) {
      selectedTask.value = existingTask;
      selectedTaskId.value = existingTask.id;
    } else {
      selectedTask.value = null;
      selectedTaskId.value = null;
    }
  } else {
    selectedTask.value = null;
    selectedTaskId.value = null;
  }
};

// 任务查询
const handleTaskQuery = (): void => {
  taskPagination.pageIndex = 1;
};

// 任务重置
const handleTaskReset = (): void => {
  taskQueryForm.taskKeyword = "";
  taskQueryForm.processName = "";
  taskQueryForm.taskOwner = "";
  taskPagination.pageIndex = 1;
};

// 任务分页大小改变
const handleTaskSizeChange = (size: number): void => {
  taskPagination.pageSize = size;
  taskPagination.pageIndex = 1;
};

// 任务页码改变
const handleTaskPageChange = (page: number): void => {
  taskPagination.pageIndex = page;
};

// 任务行点击
const handleTaskRowClick = (row: TaskItem): void => {
  selectedTask.value = row;
  selectedTaskId.value = row.id;
};

// 任务选择
const handleTaskSelect = (row: TaskItem): void => {
  selectedTask.value = row;
  selectedTaskId.value = row.id;
};

// 工序名称选择对话框
const processNameDialogVisible = ref(false);
const handleProcessNameSelect = (): void => {
  processNameDialogVisible.value = true;
};

// 确认选择工序名称
const handleConfirmProcessName = (name: string): void => {
  taskQueryForm.processName = name;
  processNameDialogVisible.value = false;
};

// 任务负责人选择对话框
const taskOwnerDialogVisible = ref(false);
const handleTaskOwnerSelect = (): void => {
  taskOwnerDialogVisible.value = true;
};

// 确认选择任务负责人
const handleConfirmTaskOwner = (name: string): void => {
  taskQueryForm.taskOwner = name;
  taskOwnerDialogVisible.value = false;
};

// 取消任务选择
const handleCancelTask = (): void => {
  taskDialogVisible.value = false;
  selectedTask.value = null;
  selectedTaskId.value = null;
};

// 确认任务选择
const handleConfirmTask = (): void => {
  if (!selectedTask.value || !selectedTaskId.value) {
    ElMessage.warning("请选择工单任务");
    return;
  }
  formModel.taskName = selectedTask.value.taskName;
  formModel.taskCode = selectedTask.value.taskCode;
  formModel.processRoute = selectedTask.value.processRoute;
  formModel.processName = selectedTask.value.processName;
  taskDialogVisible.value = false;
  selectedTaskId.value = null;
};

// 班组列表
const teamList = ref<Array<{ label: string; value: string }>>([]);

// 根据班组和关键词筛选的用户列表
const filteredUserList = computed(() => {
  let users = userList.value;

  // 按班组筛选
  if (selectedTeam.value) {
    users = users.filter((user) => user.organname === selectedTeam.value);
  }

  // 按关键词搜索
  if (userKeyword.value.trim()) {
    const keyword = userKeyword.value.trim().toLowerCase();
    users = users.filter((user) => {
      return (
        user.username?.toLowerCase().includes(keyword) ||
        user.usernumber?.toLowerCase().includes(keyword) ||
        user.organname?.toLowerCase().includes(keyword)
      );
    });
  }

  return users;
});

// 编码生成计数器，确保每次生成都不同
let codeGenerationCounter = 0;

// 生成领料单编号（基于年月日时分秒）
const generatePickMaterialCode = (): string => {
  const now = new Date();
  const pad = (n: number, len: number = 2) => `${n}`.padStart(len, "0");

  // 获取年月日时分秒
  const year = now.getFullYear();
  const month = pad(now.getMonth() + 1);
  const day = pad(now.getDate());
  const hours = pad(now.getHours());
  const minutes = pad(now.getMinutes());
  const seconds = pad(now.getSeconds());
  const milliseconds = now.getMilliseconds();

  // 获取时间戳和微秒
  const timestamp = Date.now();
  let microSeconds = 0;
  if (typeof performance !== "undefined" && performance.now) {
    const perfNow = performance.now();
    microSeconds = Math.floor((perfNow % 1) * 1000);
  } else {
    microSeconds = Math.floor(Math.random() * 1000);
  }

  // 递增计数器
  codeGenerationCounter = (codeGenerationCounter + 1) % 100000;

  // 生成唯一因子
  const timestampSuffix = timestamp.toString().slice(-4).padStart(4, "0");
  const microSecondsStr = microSeconds.toString().padStart(3, "0");
  const counterStr = codeGenerationCounter.toString().padStart(5, "0");
  const counterSuffix = counterStr.slice(-3);
  const uniqueFactor = (
    timestampSuffix +
    microSecondsStr +
    counterSuffix
  ).slice(-6);

  // 格式：LL + 年月日(8位) + 时分秒(6位) + 毫秒(3位) + 唯一因子(6位)
  const msStr = pad(milliseconds, 3);
  return (
    "LL" + year + month + day + hours + minutes + seconds + msStr + uniqueFactor
  );
};

// 处理自动生成编码开关变化
const handleAutoGenerateCodeChange = (value: boolean) => {
  if (value) {
    // 开启自动生成：每次开启都生成新的编码（基于当前年月日时分秒），禁用输入
    setTimeout(() => {
      formModel.pickMaterialCode = generatePickMaterialCode();
    }, 0);
  } else {
    // 关闭自动生成：清空编码，允许手动输入
    formModel.pickMaterialCode = "";
  }
};

// 表单数据接口
interface PickMaterialDetail {
  id?: number | null;
  pickMaterialId?: number;
  materialName: string;
  materialCode: string;
  specModel: string;
  unit: string;
  currentStock: number;
  pickQuantity: number;
  batchNo: string;
  warehouseName: string;
  itemRemark: string;
}

interface PickMaterialForm {
  id?: number;
  pickMaterialCode: string;
  pickMaterialName: string;
  pickMaterialDate: string | null;
  workOrderName: string;
  taskName: string;
  workFixtureCode: string;
  picker: string;
  workOrderCode: string;
  taskCode: string;
  partCode: string;
  processRoute: string;
  processName: string;
  workFixtureRemark: string;
  workFixtureDate: string | null;
  remark: string;
  detail: PickMaterialDetail[];
}

// 默认表单数据
const defaultFormModel: PickMaterialForm = {
  id: undefined,
  pickMaterialCode: "",
  pickMaterialName: "",
  pickMaterialDate: null,
  workOrderName: "",
  taskName: "",
  workFixtureCode: "",
  picker: "",
  workOrderCode: "",
  taskCode: "",
  partCode: "",
  processRoute: "",
  processName: "",
  workFixtureRemark: "",
  workFixtureDate: null,
  remark: "",
  detail: [],
};

const formModel = reactive<PickMaterialForm>({ ...defaultFormModel });

// 表单验证规则
const rules = reactive<FormRules>({
  pickMaterialCode: [
    { required: true, message: "领料单编号不可为空", trigger: "blur" },
  ],
  pickMaterialName: [
    { required: true, message: "领料单名称不可为空", trigger: "blur" },
  ],
  pickMaterialDate: [
    { required: true, message: "请选择领料日期", trigger: "change" },
  ],
  workOrderName: [
    { required: true, message: "工单名称不可为空", trigger: "blur" },
  ],
  taskName: [{ required: true, message: "任务名称不可为空", trigger: "blur" }],
});

// 初始化编辑数据
onMounted(() => {
  if (isEditMode.value && route.query.editData) {
    try {
      const editData = JSON.parse(
        decodeURIComponent(route.query.editData as string)
      );
      Object.assign(formModel, editData);
      // 编辑模式下，如果有编码，默认关闭自动生成功能
      if (formModel.pickMaterialCode) {
        autoGenerateCode.value = false;
      }
    } catch (error) {
      console.error("解析编辑数据失败:", error);
      ElMessage.error("加载编辑数据失败");
    }
  }
});

// 物料选择对话框相关状态
const materialDialogVisible = ref(false);
const materialLoading = ref(false);
const materialTableRef = ref();
const materialTableData = ref<PurchaseInboundOrderItem[]>([]);
const selectedMaterials = ref<PurchaseInboundOrderItem[]>([]);
const jumpPage = ref(1);

const materialSearchForm = reactive({
  materialKeyword: "",
  unit: null as string | null,
});

const materialPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  pageCount: 0,
});

// 采购入库物料接口定义
interface PurchaseInboundOrderItem {
  id: number;
  materialName: string;
  materialNo: string;
  specification: string;
  unit?: string;
  batchNo?: string;
  warehouseName?: string;
  inboundQuantity?: number;
  [key: string]: any;
}

// 获取单位选项列表（从原始数据中获取所有可用单位）
const unitOptions = computed(() => {
  const units = new Set<string>();
  rawMaterialData.value.forEach((item) => {
    if (item.unit) {
      units.add(item.unit);
    }
  });
  return Array.from(units).sort();
});

// 存储所有物料数据（用于筛选）
const allMaterialData = ref<PurchaseInboundOrderItem[]>([]);
// 存储原始物料数据（用于获取单位选项）
const rawMaterialData = ref<PurchaseInboundOrderItem[]>([]);

// 加载物料列表
const loadMaterialList = async () => {
  materialLoading.value = true;
  try {
    // 先获取所有数据，不进行分页（用于筛选）
    const params: any = {
      PageIndex: 1,
      PageSize: 9999,
    };

    if (materialSearchForm.materialKeyword) {
      params.MaterialName = materialSearchForm.materialKeyword.trim();
    }

    const res = await https.Reads.get("/Warehouse/PurchaseInboundOrder", {
      params,
    });

    const responseData = res?.data ?? {};
    const code = responseData.code ?? responseData.Code;
    let dataList: any[] = [];

    if (responseData.data !== undefined) {
      dataList = Array.isArray(responseData.data) ? responseData.data : [];
    } else if (responseData.Data !== undefined) {
      dataList = Array.isArray(responseData.Data) ? responseData.Data : [];
    }

    if (code === -1) {
      const msg = responseData.msg ?? responseData.Msg ?? "获取物料列表失败";
      ElMessage.error(msg);
      rawMaterialData.value = [];
      allMaterialData.value = [];
      materialTableData.value = [];
      materialPagination.totalCount = 0;
    } else {
      // 保存原始数据（用于获取单位选项）
      rawMaterialData.value = dataList;

      // 先应用所有筛选条件
      let filteredList = dataList;

      // 按单位筛选
      if (materialSearchForm.unit) {
        filteredList = filteredList.filter(
          (item: PurchaseInboundOrderItem) =>
            item.unit === materialSearchForm.unit
        );
      }

      // 如果在 MaterialName 参数中已经筛选了，就不需要再次筛选
      // 如果没有使用 MaterialName 参数，则在客户端进行筛选
      if (!materialSearchForm.materialKeyword || !params.MaterialName) {
        if (materialSearchForm.materialKeyword) {
          const keyword = materialSearchForm.materialKeyword
            .trim()
            .toLowerCase();
          filteredList = filteredList.filter(
            (item: PurchaseInboundOrderItem) =>
              item.materialNo?.toLowerCase().includes(keyword) ||
              item.materialName?.toLowerCase().includes(keyword)
          );
        }
      }

      // 保存所有筛选后的数据
      allMaterialData.value = filteredList;

      // 应用分页
      const startIndex =
        (materialPagination.pageIndex - 1) * materialPagination.pageSize;
      const endIndex = startIndex + materialPagination.pageSize;
      materialTableData.value = filteredList.slice(startIndex, endIndex);

      // 更新分页信息
      materialPagination.totalCount = filteredList.length;
      materialPagination.pageCount = Math.max(
        1,
        Math.ceil(filteredList.length / materialPagination.pageSize)
      );
    }
  } catch (error: any) {
    console.error("获取物料列表失败:", error);
    ElMessage.error("获取物料列表失败，请稍后重试");
    rawMaterialData.value = [];
    allMaterialData.value = [];
    materialTableData.value = [];
    materialPagination.totalCount = 0;
  } finally {
    materialLoading.value = false;
  }
};

// 物料查询
const handleMaterialQuery = () => {
  materialPagination.pageIndex = 1;
  jumpPage.value = 1;
  loadMaterialList();
};

// 物料重置
const handleMaterialReset = () => {
  materialSearchForm.materialKeyword = "";
  materialSearchForm.unit = null;
  materialPagination.pageIndex = 1;
  jumpPage.value = 1;
  selectedMaterials.value = [];
  loadMaterialList();
};

// 物料分页大小改变
const handleMaterialSizeChange = (size: number) => {
  materialPagination.pageSize = size;
  materialPagination.pageIndex = 1;
  jumpPage.value = 1;
  applyMaterialPagination();
};

// 物料页码改变
const handleMaterialPageChange = (page: number) => {
  materialPagination.pageIndex = page;
  jumpPage.value = page;
  // 只需要更新分页，不需要重新加载数据
  applyMaterialPagination();
};

// 应用物料分页
const applyMaterialPagination = () => {
  const startIndex =
    (materialPagination.pageIndex - 1) * materialPagination.pageSize;
  const endIndex = startIndex + materialPagination.pageSize;
  materialTableData.value = allMaterialData.value.slice(startIndex, endIndex);
};

// 物料跳转页面
const handleMaterialJumpPage = () => {
  const maxPage = Math.max(1, materialPagination.pageCount);
  if (jumpPage.value >= 1 && jumpPage.value <= maxPage) {
    materialPagination.pageIndex = jumpPage.value;
    applyMaterialPagination();
  } else {
    ElMessage.warning(`请输入1到${maxPage}之间的页码`);
    jumpPage.value = materialPagination.pageIndex;
  }
};

// 物料选择变化
const handleMaterialSelectionChange = (rows: PurchaseInboundOrderItem[]) => {
  selectedMaterials.value = rows;
};

// 打开物料选择对话框
const openMaterialDialog = async () => {
  materialDialogVisible.value = true;
  materialSearchForm.materialKeyword = "";
  materialSearchForm.unit = null;
  materialPagination.pageIndex = 1;
  materialPagination.pageSize = 10;
  selectedMaterials.value = [];
  jumpPage.value = 1;
  rawMaterialData.value = [];
  allMaterialData.value = [];
  await loadMaterialList();
};

// 取消物料选择
const handleCancelMaterial = () => {
  materialDialogVisible.value = false;
  selectedMaterials.value = [];
  materialSearchForm.materialKeyword = "";
  materialSearchForm.unit = null;
};

// 确认物料选择
const handleConfirmMaterial = () => {
  if (selectedMaterials.value.length === 0) {
    ElMessage.warning("请至少选择一条物料");
    return;
  }

  let addedCount = 0;
  let skippedCount = 0;

  // 将选中的物料添加到明细列表
  selectedMaterials.value.forEach((item) => {
    // 检查是否已存在相同的物料编号
    const existingIndex = formModel.detail.findIndex(
      (detail) => detail.materialCode === item.materialNo
    );

    if (existingIndex === -1) {
      // 如果不存在，添加新明细
      formModel.detail.push({
        id: null,
        pickMaterialId: formModel.id,
        materialName: item.materialName || "",
        materialCode: item.materialNo || "",
        specModel: item.specification || "",
        unit: item.unit || "",
        currentStock: 0,
        pickQuantity: 0,
        batchNo: item.batchNo || "",
        warehouseName: item.warehouseName || "",
        itemRemark: "",
      });
      addedCount++;
    } else {
      skippedCount++;
    }
  });

  // 显示添加结果
  if (addedCount > 0 && skippedCount > 0) {
    ElMessage.success(
      `已添加 ${addedCount} 条物料明细，${skippedCount} 条已存在已跳过`
    );
  } else if (addedCount > 0) {
    ElMessage.success(`已添加 ${addedCount} 条物料明细`);
  } else {
    ElMessage.warning("所选物料均已存在，未添加新明细");
  }

  materialDialogVisible.value = false;
  selectedMaterials.value = [];
  materialSearchForm.materialKeyword = "";
  materialSearchForm.unit = null;
};

// 添加物料明细 - 打开物料选择对话框
const handleAddDetail = () => {
  openMaterialDialog();
};

// 删除物料明细
const handleRemoveDetail = (index: number) => {
  ElMessageBox.confirm("确认要删除该物料明细吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      formModel.detail.splice(index, 1);
      ElMessage.success("删除成功");
    })
    .catch(() => {
      // 取消删除
    });
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    if (formModel.detail.length === 0) {
      ElMessage.warning("请至少添加一条物料明细");
      return;
    }

    // 验证明细必填项
    for (let i = 0; i < formModel.detail.length; i++) {
      const item = formModel.detail[i];
      if (
        !item ||
        !item.materialName ||
        !item.materialCode ||
        !item.pickQuantity
      ) {
        ElMessage.warning(
          `物料明细 ${i + 1} 的物料名称、物料编号和领用数量为必填项`
        );
        return;
      }
    }

    submitLoading.value = true;

    // 构建请求数据
    const requestData = {
      ...(isEditMode.value ? { id: formModel.id || 0 } : {}),
      pickMaterialCode: formModel.pickMaterialCode,
      pickMaterialName: formModel.pickMaterialName || "",
      pickMaterialDate: formModel.pickMaterialDate,
      workOrderName: formModel.workOrderName,
      taskName: formModel.taskName,
      workFixtureCode: formModel.workFixtureCode || "",
      picker: formModel.picker || "",
      workOrderCode: formModel.workOrderCode || "",
      taskCode: formModel.taskCode || "",
      partCode: formModel.partCode || "",
      processRoute: formModel.processRoute || "",
      processName: formModel.processName || "",
      workFixtureRemark: formModel.workFixtureRemark || "",
      workFixtureDate: formModel.workFixtureDate,
      remark: formModel.remark || "",
      detail: formModel.detail.map((item) => ({
        ...(isEditMode.value ? { id: item.id || null } : {}),
        materialName: item.materialName,
        materialCode: item.materialCode,
        specModel: item.specModel || "",
        unit: item.unit || "",
        currentStock: item.currentStock || 0,
        pickQuantity: item.pickQuantity,
        batchNo: item.batchNo || "",
        warehouseName: item.warehouseName || "",
        itemRemark: item.itemRemark || "",
      })),
    };

    const apiPath = isEditMode.value
      ? "/Warehouse/ProducePickUpdate"
      : "/Warehouse/ProducePickAdd";

    // 编辑模式使用 PUT，新增模式使用 POST
    const res = isEditMode.value
      ? await https.Writes.put(apiPath, requestData)
      : await https.Writes.post(apiPath, requestData);

    const responseData = res?.data ?? {};
    const code = responseData.code ?? responseData.Code;
    const msg = responseData.msg ?? responseData.Msg ?? "操作成功";

    if (code === 1) {
      ElMessage.success(msg);
      router.push("/PickMaterialList");
    } else {
      throw new Error(msg || "操作失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("提交失败:", error);
      const errMessage =
        error?.response?.data?.msg ??
        error?.response?.data?.Msg ??
        error?.message ??
        "操作失败，请稍后重试";
      ElMessage.error(errMessage);
    }
  } finally {
    submitLoading.value = false;
  }
};

// 取消
const handleCancel = () => {
  ElMessageBox.confirm("确认要取消吗？未保存的数据将丢失", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      router.push("/PickMaterialList");
    })
    .catch(() => {
      // 取消操作
    });
};

// 获取用户列表
const fetchUserList = async (): Promise<void> => {
  if (userLoading.value) return;
  userLoading.value = true;
  try {
    const res = await https.Reads.get<ApiPageing<UserDto>>("/RBAC/ShowUser", {
      params: { pageindex: 1, pagesize: 1000 },
    });
    const payload = res?.data ?? ({} as ApiPageing<UserDto>);
    const code = payload.code ?? payload.Code ?? 0;

    if (code === 1) {
      const list = payload.data ?? payload.Data ?? [];
      userList.value = list;

      // 提取班组列表（从 organname 字段）
      const teamSet = new Set<string>();
      list.forEach((user: UserDto) => {
        if (user.organname) {
          teamSet.add(user.organname);
        }
      });
      teamList.value = Array.from(teamSet)
        .sort()
        .map((team) => ({ label: team, value: team }));
    } else {
      ElMessage.error(payload.msg ?? payload.Msg ?? "获取用户列表失败");
    }
  } catch (error: any) {
    console.error("获取用户列表失败:", error);
    ElMessage.error("获取用户列表失败，请稍后重试");
    userList.value = [];
  } finally {
    userLoading.value = false;
  }
};

// 打开用户选择对话框
const openUserDialog = (): void => {
  userDialogVisible.value = true;
  userKeyword.value = "";
  selectedTeam.value = null;

  // 如果已有选中的领料人，设置为选中状态
  if (formModel.picker) {
    const existingUser = userList.value.find(
      (user) => user.username === formModel.picker
    );
    if (existingUser) {
      selectedUser.value = existingUser;
      selectedTeam.value = existingUser.organname || null;
    } else {
      selectedUser.value = null;
    }
  } else {
    selectedUser.value = null;
  }

  // 如果用户列表为空，则获取
  if (userList.value.length === 0) {
    fetchUserList();
  }
};

// 选择班组
const handleTeamSelect = (teamValue: string): void => {
  selectedTeam.value = selectedTeam.value === teamValue ? null : teamValue;
};

// 选择用户
const handleUserSelect = (user: UserDto): void => {
  selectedUser.value = user;
};

// 移除已选择的用户
const handleRemoveSelectedUser = (): void => {
  selectedUser.value = null;
};

// 取消选择
const handleCancelUser = (): void => {
  userDialogVisible.value = false;
  selectedUser.value = null;
  userKeyword.value = "";
  selectedTeam.value = null;
};

// 确认选择
const handleConfirmUser = (): void => {
  if (!selectedUser.value) {
    ElMessage.warning("请选择领料人");
    return;
  }
  formModel.picker = selectedUser.value.username || "";
  userDialogVisible.value = false;
  userKeyword.value = "";
  selectedTeam.value = null;
};
</script>

<style scoped>
.pick-material-add-page {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding-bottom: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 面包屑卡片 */
.breadcrumb-card {
  border-radius: 14px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.25);
  color: #fff;
}

.breadcrumb-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.breadcrumb-title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.breadcrumb-icon {
  font-size: 32px;
  color: #fff;
}

.breadcrumb-subtitle {
  margin: 0;
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
}

.breadcrumb-heading {
  margin: 0;
  font-size: 22px;
  font-weight: 700;
  color: #fff;
}

:deep(.breadcrumb-card .el-breadcrumb) {
  color: rgba(255, 255, 255, 0.9);
}

:deep(.breadcrumb-card .el-breadcrumb__inner) {
  color: rgba(255, 255, 255, 0.9);
}

:deep(.breadcrumb-card .el-breadcrumb__separator) {
  color: rgba(255, 255, 255, 0.7);
}

/* 表单卡片 */
.form-card {
  border-radius: 14px;
  border: none;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  background: #fff;
  padding: 30px;
}

.page-header {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #f0f2f5;
}

.page-header__content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.page-header__title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-header__icon-wrapper {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-header__icon {
  font-size: 24px;
  color: #fff;
}

.page-header__text h2 {
  margin: 0 0 4px 0;
  font-size: 20px;
  font-weight: 700;
  color: #303133;
}

.page-header__desc {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.page-header__tag {
  padding: 8px 16px;
  font-size: 14px;
}

.tag-icon {
  margin-right: 4px;
}

/* 表单区块 */
.form-section {
  margin-bottom: 30px;
  padding: 24px;
  background: #fafbfc;
  border-radius: 12px;
  border: 1px solid #e4e7ed;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e4e7ed;
}

.section-header__main {
  display: flex;
  align-items: center;
  gap: 12px;
}

.section-header__icon {
  font-size: 20px;
  color: #667eea;
}

.section-title {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.section-subtitle {
  margin: 0;
  font-size: 13px;
  color: #909399;
}

.section-header__actions {
  display: flex;
  gap: 10px;
}

.add-detail-btn {
  border-radius: 8px;
}

/* 明细项 */
.detail-item {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.detail-item__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f2f5;
}

.detail-item__title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.detail-item__icon {
  color: #667eea;
}

.detail-form {
  margin-top: 16px;
}

.empty-detail {
  padding: 40px 20px;
  text-align: center;
}

/* 表单操作按钮 */
.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.form-actions .el-button {
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 500;
}

/* 编码字段样式 */
.code-field-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
}

.code-input {
  flex: 1;
}

.code-switch-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
  margin-left: 8px;
}

.code-switch-label {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  color: #606266;
  white-space: nowrap;
}

.code-switch-label .el-icon {
  font-size: 14px;
}

:deep(.code-switch-wrapper .el-switch) {
  --el-switch-on-color: #409eff;
}

/* 领料人字段样式 */
.picker-field-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.picker-select-btn {
  flex-shrink: 0;
  border-radius: 6px;
}

/* 选择字段样式 */
.select-field-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.select-btn {
  flex-shrink: 0;
  border-radius: 6px;
}

/* 用户选择对话框样式 */
.picker-user-dialog {
  --el-dialog-padding-primary: 20px;
}

.selected-items {
  margin-bottom: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.selected-tag {
  font-size: 14px;
  padding: 6px 12px;
}

.search-box {
  margin-bottom: 16px;
}

.search-input {
  width: 100%;
}

.dialog-content {
  display: flex;
  gap: 16px;
  height: 400px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
}

/* 左侧班组列表 */
.team-list-container {
  width: 200px;
  border-right: 1px solid #e4e7ed;
  background: #fafbfc;
  display: flex;
  flex-direction: column;
}

.team-list-header {
  padding: 12px 16px;
  font-weight: 600;
  font-size: 14px;
  color: #303133;
  background: #f0f2f5;
  border-bottom: 1px solid #e4e7ed;
}

.team-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

.team-item {
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s;
  color: #606266;
  font-size: 14px;
}

.team-item:hover {
  background: #f0f2f5;
  color: #409eff;
}

.team-item.active {
  background: #e6f4ff;
  color: #409eff;
  font-weight: 500;
}

/* 右侧人员列表 */
.user-list-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.user-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.user-item {
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s;
  border-radius: 4px;
  margin-bottom: 4px;
}

.user-item:hover {
  background: #f5f7fa;
}

.user-item.selected {
  background: #e6f4ff;
}

.user-radio {
  width: 100%;
  margin: 0;
}

.user-radio :deep(.el-radio__label) {
  font-size: 14px;
  color: #303133;
  padding-left: 8px;
}

.user-name {
  font-size: 14px;
  color: #303133;
}

.empty-user {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 工单选择对话框样式 */
.work-order-dialog {
  --el-dialog-padding-primary: 20px;
}

.dialog-search-area {
  margin-bottom: 16px;
  padding: 16px;
  background: #fafbfc;
  border-radius: 6px;
}

.search-form {
  margin: 0;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
}

.work-order-table {
  margin-top: 16px;
}

.radio-with-index {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 0 8px;
}

.work-order-radio {
  margin-right: 0;
  flex-shrink: 0;
}

.work-order-radio :deep(.el-radio__input) {
  cursor: pointer;
}

.work-order-radio :deep(.el-radio__label) {
  padding-left: 0;
  display: none;
}

.index-number {
  font-size: 14px;
  color: #606266;
  font-weight: 400;
  min-width: 24px;
  text-align: center;
  flex-shrink: 0;
}

.dialog-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

/* 任务选择对话框样式 */
.task-dialog {
  --el-dialog-padding-primary: 20px;
}

.task-dialog-header {
  display: flex;
  gap: 24px;
  margin-bottom: 16px;
  padding: 12px 16px;
  background: #f5f7fa;
  border-radius: 6px;
}

.work-order-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.info-value {
  font-size: 14px;
  color: #303133;
  font-weight: 600;
}

.task-table {
  margin-top: 16px;
}

.task-radio {
  margin-right: 0;
  flex-shrink: 0;
}

.task-radio :deep(.el-radio__input) {
  cursor: pointer;
}

.task-radio :deep(.el-radio__label) {
  padding-left: 0;
  display: none;
}

.select-input-wrapper {
  display: flex;
  align-items: center;
  gap: 4px;
}

.select-icon-btn {
  padding: 8px 12px;
  flex-shrink: 0;
  min-width: 40px;
}

.select-icon-btn :deep(.el-icon) {
  font-size: 16px;
}

.option-list {
  max-height: 400px;
  overflow-y: auto;
}

.option-item {
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s;
  border-radius: 4px;
  margin-bottom: 4px;
  font-size: 14px;
  color: #606266;
}

.option-item:hover {
  background: #f5f7fa;
  color: #409eff;
}

/* 物料选择对话框样式 */
.material-select-dialog {
  --el-dialog-padding-primary: 20px;
}

.material-dialog-search {
  margin-bottom: 16px;
  padding: 16px;
  background: #fafbfc;
  border-radius: 6px;
}

.material-search-form {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.material-search-form {
  margin: 0;
}

.material-search-form :deep(.el-form-item) {
  margin-bottom: 0;
}

.material-table {
  margin-top: 16px;
}

.material-dialog-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
  padding: 12px 0;
}

.pagination-total {
  font-size: 14px;
  color: #606266;
}

.pagination-jumper {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
}

.pagination-jumper :deep(.el-input-number) {
  line-height: 1;
}

.pagination-jumper :deep(.el-input-number .el-input__wrapper) {
  padding: 4px 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .pick-material-add-page {
    padding: 12px;
  }

  .form-card {
    padding: 20px;
  }

  .page-header__content {
    flex-direction: column;
    align-items: flex-start;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .form-actions {
    flex-direction: column;
  }

  .form-actions .el-button {
    width: 100%;
  }

  .code-field-wrapper {
    flex-direction: column;
    align-items: flex-start;
  }

  .code-switch-wrapper {
    width: 100%;
    margin-top: 8px;
  }
}
</style>
